import './video.css'
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { actionCreators } from '../home/store/index'
import { withRouter } from 'react-router-dom'
import { addCart } from '../home/store/actionCreators'
import { removeCart } from '../cart/store/actionCreators'
import { changeShowLogin } from '../../components/header/store/actionCreators'
// import { getVideoItem } from '../live/store/actionCreators'

import api from '../../api/api'

import {
  CourseItemWrapper,
  CourseTitle,
  CourseImgWrapper,
  ItemWrapper,
  CourseListWrapper,
  Wrapper
} from './style'

import {Button, Icon, message, Modal} from 'antd';
import utils from '../../common/utils';
class CourseItem extends Component {
  constructor(props) {
    super(props)
    this.state = {
      visible: false,
      endTime: false,
      name: '',
      url: '',
      type: 'application/x-mpegURL',
      nc: null
    }
  }

  componentDidMount() {
    let id = this.props.match.params.id
    if(id) {
      this.props.getCourseItem({
        lessonId: id
      })
    }
  }

  // 跳转视频播放页面
  toPayVideo(id) {
    if(this.props.courseItem.get('shoppingStatus') === '已经购买' || this.props.courseItem.get('shoppingStatus') === '免费') {
      // this.props.history.push({
      //   pathname: '/live/' + id
      // })
      if(utils.local('userData')) {
        window.location.href="/live?roomId=" + id
      }else {
        message.error('您未登录,请先登录。如已登录,请刷新页面！')
      }
    }else if(this.props.courseItem.get('shoppingStatus') === '用户未登录购买情况未知') {
      message.error('您未登录,请先登录。如已登录,请刷新页面！')
    }
    else {
      message.error('您未购买改课程,请先购买！')
    }
    
  }
  
  tryWatch(obj) {
    // this.props. 
    let roomId = obj.get('roomId')
    if(roomId) {
      api.getVideoUrl({
        roomId
      }).then(res => {
        let url = res.data.m3u8_lsd_url  //res.data.pull_url
        let type = 'application/x-mpegURL'
        this.setState({
          visible: true,
          endTime: false,
          name: obj.get('name'),
          url,
          type
        })
        debugger
        if(!document.getElementById('try-watch')) {
          var x = document.createElement("VIDEO");
          x.setAttribute('class', 'video-js vjs-default-skin vjs-big-play-centered')
          x.setAttribute('id', 'try-watch')
          x.setAttribute('data-setup', '{}')
          x.setAttribute('autoplay', true)
          x.controls = true
          x.preload = 'auto'
          x.style.width = '600px'
          x.style.height = '375px'

          let s = document.createElement("SOURCE");
          s.setAttribute('id', 'source')
          s.setAttribute('src', url)
          s.setAttribute('type', type)

          x.appendChild(s)
          document.getElementById('videoContainer').appendChild(x)

        }

        window.myVideo = window.videojs('try-watch', {
          bigPlayButton: true,
          textTrackDisplay: false,
          posterImage: false,
          errorDisplay: false,
        })
        // window.myVideo.autoPlay()
        window.myVideo.play()
       


        // if(!window.myVideo) {
        //   window.myVideo = window.videojs('try-watch', {
        //     bigPlayButton: true,
        //     textTrackDisplay: false,
        //     posterImage: false,
        //     errorDisplay: false,
        //   })
        //   window.myVideo.play()
        // }else {
        //   debugger
        //   window.myVideo.src({url, type})
        //   window.myVideo.load(url);
        // }
       
        let end_time = res.data.trial_limit_time ? res.data.trial_limit_time : 180000
        setTimeout(() => {
          this.setState({
            endTime: true
          })
        }, end_time);
      }) 
    }
  }

  addCart() {
    let status = this.props.courseItem.get('shoppingStatus')
    let id = this.props.courseItem.get('lessonId')
    if(status === '已加入购物车'){
      this.props.removeCart({
        lessonId: id
      })
      let uid = this.props.match.params.id
      if(uid) {
        setTimeout(()=> {
          this.props.getCourseItem({
            lessonId: uid
          })
        }, 300)
      }
    }else {
      if(localStorage.getItem('userData')) {
        this.props.addCart(id)
        let uid = this.props.match.params.id
        if(uid) {
          setTimeout(()=> {
            this.props.getCourseItem({
              lessonId: uid
            })
          }, 300)
        }
      } else {
        this.props.changeLogin(true)
      } 
    }
  }
  handleCancel() {
    // window.v = document.getElementById('try-watch')
    window.myVideo.dispose()
    this.setState({
      visible: false,
      endTime: false
    })
  }

  checkCourse(idx) {
    if(this.state.nc === idx) {
      return
    }
    this.setState({
      nc: idx
    })
  }

  render() {
    return (
      <Wrapper>
        {
          this.props.courseItem ? (
            <div>
              <CourseItemWrapper>
                <CourseTitle>
                  {this.props.courseItem.get('lessonName')}
                  <CourseImgWrapper className="clearfix">
                    <img src={this.props.courseItem.get('coverUrl')} />
                    <ItemWrapper>
                      <p>价格：<span className="price">￥{this.props.courseItem.get('lessonPrice')}</span></p>
                      <p>主讲：{this.props.courseItem.get('teacherName')}</p>
                      <p>总课时：{this.props.courseItem.get('lessonPeriodAmount')}</p>
                      {
                        this.state.nc ? <p>现课时：{this.state.nc}</p> : ''
                      }
                      <p>总人数：{this.props.courseItem.get('learnedPerson')}</p>
                      <p>评分：<span className="rate">{this.props.courseItem.get('lessonScore')}</span></p>
                      {
                        this.props.courseItem.get('shoppingStatus') === '已经购买' ||  this.props.courseItem.get('shoppingStatus') === '免费'? '' : <Button type="primary" onClick={this.addCart.bind(this)}>{this.props.courseItem.get('shoppingStatus') === '已加入购物车' ? '移除购物车': '加入购物车'}</Button>
                      }
                    </ItemWrapper>
                  </CourseImgWrapper>
                </CourseTitle>
              </CourseItemWrapper>
              <CourseListWrapper style={{minHeight: (document.body.clientHeight - 508 + 'px')}}>
                  <p className="catalog">目录（{this.props.courseItem.get('data') && this.props.courseItem.get('data').size}）</p>
                  <ul>
                    {
                      this.props.courseItem.get('data') ? this.props.courseItem.get('data').map((item, idx)=> {
                        return (
                          <li key={idx}>
                            <span className="sort">{idx+1}</span>
                            <p>
                              <span className="courseName">{item.get('period')}</span>
                              {item.get('name')}
                            </p>
                            <span className="play">
                              {
                                item.get('isTrial')==='true' ? <a href="#" onClick={this.tryWatch.bind(this, item)} style={{fontSize: '16px', marginRight: '10px'}}><Icon style={{fontSize: '20px', verticalAlign: 'middle',lineHeight:'20px' }} type="caret-right" />试听一下</a> : ''
                              }
                              {
                                item.get('status') === '进行中' ? this.checkCourse(idx+1) : ''
                              }
                              {
                                item.get('roomId') ? <a href="#" style={{fontSize: '16px'}} onClick={()=> this.toPayVideo(item.get('roomId'))}>
                                  <Icon type="youtube" style={{fontSize: '20px', verticalAlign: 'middle',lineHeight:'20px' }} />
                                  <span style={{fontSize: '16px', marginLeft: '4px'}}>{item.get('status')}</span>
                                </a>: <span style={{fontSize: '16px', color: '#8BCA31'}}>{item.get('status')}</span>
                              }
                            </span>
                          </li>
                        )
                      }) : ''
                    }
                  </ul>
                </CourseListWrapper>
            </div>
          ): ''
        }
        <Modal
          title={this.state.name + '试听'}
          visible={this.state.visible}
          onCancel={this.handleCancel.bind(this)}
          wrapClassName="diy-modal"
          closable={true}
          maskClosable={true}
          width={648}
          footer={null}
        >
          {
            this.state.endTime ? <div style={{textAlign: 'center', marginBottom: '40px'}}>
              <img src={require('./buy.png')} />
            </div> : <div style={{background: '#000'}} id="videoContainer"> 
                <video id="try-watch" className="video-js vjs-default-skin vjs-big-play-centered" controls preload="auto" autoplay="autoplay"  data-setup='{}' style={{width: '600px', height: '375px'}}>
                  <source id="source" src={this.state.url} type={this.state.type}></source>
                </video>
              {/* <div id="try-watch" style={{width: '600px', height: '375px'}}></div> */}
            </div>
          }
        </Modal>
      </Wrapper>
    )
  }
}


const mapState = (state) => ({
  courseItem: state.getIn(['home', 'courseDescript'])
})

const mapDispatch = (dispatch) => ({
  getCourseItem(params) {
    dispatch(actionCreators.getCourseDescript(params))
  },
  addCart(lessonId) {
    dispatch(addCart({
      lessonId
    }))
  },
  removeCart(params) {
    dispatch(removeCart(params))
  },
  changeLogin(params) {
    dispatch(changeShowLogin(params))
  },
  // getVideoItem(params) {
  //   dispatch(getVideoItem(params))
  // }
})



export default connect(mapState, mapDispatch)(withRouter(CourseItem))